%加载数据集
x_train=loadMNISTImages('E:\studyApps\jupyterfile\动手学Pytorch\data\FashionMNIST\raw\train-images-idx3-ubyte');
x_test=loadMNISTImages('E:\studyApps\jupyterfile\动手学Pytorch\data\FashionMNIST\raw\t10k-images-idx3-ubyte');
y_train=loadMNISTLabels('E:\studyApps\jupyterfile\动手学Pytorch\data\FashionMNIST\raw\train-labels-idx1-ubyte');
y_test=loadMNISTLabels('E:\studyApps\jupyterfile\动手学Pytorch\data\FashionMNIST\raw\t10k-labels-idx1-ubyte');
 
% transpose 转置后，每一行为一幅图像 变为一个number*pixel的矩阵
x_train=x_train';
x_train = sparse(x_train);% 转化为稀疏矩阵后，速度提升很多5.41/7.79大概速度
x_test=x_test';
x_test = sparse(x_test);


%{
x_testF = x_test;
x_testF = sparse(x_testF);
[rows, cols] = size(x_test);  
disp(rows);
disp(cols);
x_train = x_train(1:60000,:);


hogFeaturesAll = zeros(60000, 324);  
hogFeaturesAll2 = zeros(rows, 324);  
for i = 1:60000  
    currentImage = x_train(i, :);  
    currentImage = reshape(currentImage,28,28);
    hogFeatures = extractHOGFeatures(currentImage, 'CellSize', [6 6]); % 使用相同的参数  
    hogFeaturesAll(i, :) = hogFeatures(:); % 将特征存储到特征矩阵中 
end 

for i = 1:rows
    currentImage2 = x_test(i, :);  
    currentImage2 = reshape(currentImage2,28,28);
    hogFeatures2 = extractHOGFeatures(currentImage2, 'CellSize', [6 6]); % 使用相同的参数  
    hogFeaturesAll2(i, :) = hogFeatures2(:); % 将特征存储到特征矩阵中 
end
x_train  = hogFeaturesAll;
x_test = hogFeaturesAll2;


 
% linear SVM
tic;% 计时
options='-t 0 -c 4 -g 0.015625 -q'; % 设置训练参数
% model=svmtrain(y_train(1:60000), x_train(1:60000,:), options); % 训练数据得到模型
model=svmtrain(y_train(1:600), x_train(1:600,:), options); % 训练数据得到模型
[y_predict,accuracy,prob_estimates]=svmpredict(y_test, x_test, model); % 利用模型进行预测
fprintf('Time: %0.2f minutes. \n', toc/60); % 显示训练过程用时，单位分钟
toc % 结束计时，自动显示所用时间，单位秒
ThreePerClsShow(x_test, y_test, y_predict); 
% 在测试集中挑选每个类别的三张图像进行显示，左下角为标签值，右下角为训练后的预测值
 
function ThreePerClsShow(x_test, y_test, y_predict)
% 在测试集中挑选每个类别的三张图像进行显示，左下角为标签值，右下角为训练后的预测值
for i=0:9 
    index = find(y_test==i,3); % 寻找第i类别的三个实例，返回其所在位置
    figure(i+2);
    for j=1:3
        TImage = full(reshape(x_test(index(j),:),[28,28]));% 将稀疏矩阵转化为非稀疏矩阵
        %TImage = reshape(x_test(index(j),:),18,18);
        subplot(1,3,j);
        imshow(TImage);
        text(2,26,num2str(y_test(index(j))),'Color','w');
        text(26,26,num2str(y_predict(index(j))),'Color','w');
    end
    title(['手写数字',num2str(i),'的预测(左下方数据为标签值，右下方为预测值)']);
    set(gcf,'position',[200,300,600,300]);
end
end
